package com.gdougms.controller;

import com.gdougms.entity.HttpMessage;
import com.gdougms.service.UserService;
import com.gdougms.tools.MailSenderTool;
import com.gdougms.tools.RandomCode;
import com.gdougms.tools.RedisCodeGetSet;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;


@Api(value = "体育馆管理系统验证码接口" ,tags = {"体育馆管理系统验证码接口"})
@Slf4j
@RestController()
public class VerifyCodeController {
    @Autowired
    UserService userService;

    @Autowired
    ObjectFactory<HttpMessage> httpMessageObjectFactory;

    @Autowired
    HttpSession httpSession;

    @Autowired
    MailSenderTool mailSenderTool;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    RedisCodeGetSet redisCodeGetSet;


    //请求获取验证码
    @ApiOperation(value = "获取验证码" , notes = "用于找回密码、修改密码、绑定邮箱等操作")
    @GetMapping("/getCode")
    public HttpMessage getCode(@RequestParam String email){
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();
        String code = RandomCode.creatCode();

        //写入redis
        HttpMessage message = redisCodeGetSet.writeCode(email,code);
        log.info("写入redis");
        if (message.getResult()){
            try {
                mailSenderTool.sendSimpleMail(email,"体育馆管理系统验证码","您的验证码为:"+ code +"，请勿轻易告知他人，请尽快进行验证。");
                log.info("发送email");
            } catch (Exception e) {
                e.printStackTrace();
                log.warn(String.valueOf(e));
                httpMessage.setResult(false);
                httpMessage.setCode(-1);
                httpMessage.setMessage("验证码发送失败！");
                return httpMessage;
            }
            httpMessage.setResult(true);
            httpMessage.setCode(200);
            httpMessage.setMessage("验证码发送成功！");
        }else {
            httpMessage.setResult(false);
            httpMessage.setCode(-1);
            httpMessage.setMessage(message.getMessage());
        }




        log.info("/getCode HttpMsg:"+httpMessage+"  code: "+code);
        return httpMessage;
    }
}
